;
(function (window, angular) {
    'use strict';
    angular.module("app.client", ["pascalprecht.translate", "ui.router", "ngSanitize", "ui.bootstrap", "angular.filter", "YB.Widget", "toaster", "Directive.All", "Controller.All", "Service.All", "Filter.All", "ckeditor", "template-directive", "template-widget", "PrintHTMLTemplate"])
        .run(["$document", "$rootScope", "ybHttp", "ybConfig", "$state", function ($document, $rootScope, ybHttp, ybConfig, $state) {
            ybConfig.initConfig();
        }])

        .config(['$qProvider', '$locationProvider', function($qProvider, $locationProvider) {
            // 禁用默认的警告日志（可选）
            $qProvider.errorOnUnhandledRejections(false);

            // Hashbang 模式 改成 普通哈希模式
            $locationProvider.hashPrefix('');
        }])

        // 国际化
        .config(["$translateProvider", function ($translateProvider) {

            $translateProvider.preferredLanguage(localStorage.getItem('lang') || 'zh-CN');

            $translateProvider.useStaticFilesLoader({
                prefix: 'i18n/',
                suffix: '.json'
            });
        }])

        .config(['$stateProvider', '$urlRouterProvider', "$logProvider", function ($stateProvider, $urlRouterProvider, $logProvider) {
            $logProvider.debugEnabled(true);

            $stateProvider.state("app", {
                url: "",
                abstract: true,
                templateUrl: "view/app.html"
            });

            $stateProvider.state("app.workBoard", {
                url: "/workBoard",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.basicData", {
                url: "/basicData",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.enterprise", {
                url: "/enterprise",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.sales", {
                url: "/sales",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.purchase", {
                url: "/purchase",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.stock", {
                url: "/stock",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.logistics", {
                url: "/logistics",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.barcode", {
                url: "/barcode",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.report", {
                url: "/report",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.personal", {
                url: "/personal",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.account", {
                url: "/account",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.corruption", {
                url: "/corruption",
                abstract: true,
                template: "<div ui-view></div>"
            });

            $stateProvider.state("app.maintenance", {
                url: "/maintenance",
                abstract: true,
                template: "<div ui-view></div>"
            });
        }])

        .controller("AppCtrl", ['$translate', '$rootScope', '$scope', "$state", "ybHttp", "UserContextService", "ybWidget", "EventBus", "$timeout", "ybConfig", function ($translate, $rootScope, $scope, $state, ybHttp, UserContextService, ybWidget, EventBus, $timeout, ybConfig) {
            const noClickSideBarStates = ['app.workBoard.main', 'app.personal.info', 'app.personal.changePwd', 'app.corruption.dashboard'];

            $scope.curState = $state;

            $rootScope.primaryMenuItem = { children: [] }; // 和 subMenu 记录的一致
            $scope.app = {
                settings: {
                    sideBar: false
                }
            };
            $scope.allMenus = []; // 所有菜单（所有一级菜单及其子菜单）
            $rootScope.subMenu = {}; // 当前菜单（一级菜单及其子菜单）
            var curMenuStateName = "";

            $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
                curMenuStateName = toState.name;

                $scope.sysName = setWebTile(curMenuStateName);

                // 判断当前页面的公共组件 是否允许国际化
                $rootScope.allowI18n = toState.is18n;

                // $scope.subMenu是异步请求获取数据，没有数据之前(id为空),侧边栏隐藏(sideBar为false)
                $scope.app.settings.sideBar = $scope.subMenu.id && !noClickSideBarStates.includes(curMenuStateName);
            });

            $scope.shadeInfo = {
                isShow: false,
                message: ""
            };
            $scope.$on("showLoading", function (event, msg) {
                $scope.shadeInfo.isShow = true;
                $scope.shadeInfo.message = msg || '加载中...';
            });
            $scope.$on("hideLoading", function (event) {
                $scope.shadeInfo.isShow = false;
            });

            /*********************** 跳转产品开始 ***********************/

            var partsBaseUrl = ybConfig.getConfig().baseUrl.PartsBaseUrl || '';
            var partsSessionId = ybConfig.getConfig().baseUrl.PartsSessionId || '';
            var partsStates = ybConfig.getConfig().baseUrl.PartsStates || [];

            function createPartsUrl(data) {
                angular.forEach(data, function (item) {
                    if (item.children && item.children.length > 0) {
                        createPartsUrl(item.children);
                    } else {
                        if (partsStates.indexOf(item.state) != -1) {
                            item.partsUrl = partsBaseUrl + item.url + "?sessionId=" + partsSessionId + "&BJ_SESSION=";
                        }
                    }
                })
            }

            /*********************** 跳转产品结束 ***********************/


            function getAuthMenu() {
                var service = "auth";
                var reqUrl = "/menu/authorized";
                ybHttp.Get(service, reqUrl).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    $scope.allMenus = resp.value;

                    afterGetAuthMenu();
                });
            }

            function afterGetAuthMenu() {
                $scope.navWidth = {
                    width: $scope.allMenus.length * 115 + "px"
                };

                const hideMeaus = ['app.main', 'xgapp']
                angular.forEach($scope.allMenus, function (item) {
                    // 隐藏不需要展示出来的一级菜单
                    if (hideMeaus.includes(item.state)) {
                        item.hidden = true;
                    }

                    // 廉情预警--菜单展示改造
                    if(item.state=='app.corruption') {
                        if (item.children.length > 0) {
                            item.children.unshift({
                                name: '廉情预警首页',
                                state: 'app.corruption.dashboard',
                                leaf: 1,
                                children: [],
                            })
                        }
                    }

                    // 跳转新零售产品-路径处理
                    if (item.children && item.children.length > 0) {
                        createPartsUrl(item.children)
                    }
                });

                if (!curMenuStateName) {
                    if ($scope.allMenus.length === 1 && $scope.allMenus[0].state == 'app.corruption') {
                        // 用户只有廉情预警菜单权限时，跳转到廉情预警dashboard页
                        $rootScope.primaryMenuItem = $scope.allMenus[0];
                        $rootScope.subMenu = angular.copy($scope.allMenus[0]);

                        $state.go("app.corruption.dashboard");
                    } else {
                        $state.go("app.workBoard.main");
                    }
                } else {
                    setSubMenu();

                    if (curMenuStateName.includes('app.corruption')) {
                        // 如果是在廉情预警其他子菜单下，刷新时 跳转到廉情预警dashboard页(dashboard页 重新组装完廉情预警菜单后，将会跳转到当前菜单curMenuStateName)
                        $state.go("app.corruption.dashboard", { fromState: curMenuStateName });
                    }
                }

                $scope.sysName = setWebTile($state.current.name);
            }

            function setWebTile(state) {
                var obj = {};
                getMenuState($scope.allMenus);

                function getMenuState(menuList) {
                    angular.forEach(menuList, function (item) {
                        obj[item.state] = item.name;
                        if (item.children.length > 0) {
                            getMenuState(item.children);
                        }
                    });
                }
                return obj[state] || window.AppData.config.otherData.sysName;
            }

            function setSubMenu() {
                var curMenuParentStateName = "app." + curMenuStateName.split(".")[1];
                var menuHasState = false;
                for (let item of $scope.allMenus) {
                    if (item.state === curMenuParentStateName) {
                        menuHasState = true;
                        $rootScope.primaryMenuItem = item;
                        $rootScope.subMenu = angular.copy(item);
                        $scope.app.settings.sideBar = !noClickSideBarStates.includes(curMenuStateName);
                        EventBus.Publish("setCrumbsItem", item);
                        break;
                    }
                }
                if (!menuHasState) {
                    $scope.subMenu.children = [];
                }
            }

            function getTargetState(menuData) {
                const childItem = menuData.children[0] || {};
                if (childItem.leaf === 1 && childItem.state !== "") {
                    return childItem.state;
                }

                if (childItem.leaf === 0) {
                    childItem.isCollapsed = false;
                    var childChildItem = childItem.children[0] || {};
                    return childChildItem.state;
                }
            }

            // 上部菜单区域切换
            $scope.clickTopMenu = function (primaryMenu, isNewBlank, e) {
                e && e.stopPropagation(); // 阻止向上冒泡

                if (primaryMenu.children.length > 0) {
                    if (!isNewBlank) {
                        $rootScope.primaryMenuItem = primaryMenu;
                        $rootScope.subMenu = angular.copy(primaryMenu);
                        $state.go(getTargetState($scope.subMenu))
                    } else {
                        window.open($state.href(getTargetState(primaryMenu)), '_blank')
                    }
                }
            };

            // 左侧菜单区域切换
            $scope.clickLeftMenu = function (subMenu) {
                if (subMenu.children.length > 0) {
                    subMenu.isCollapsed = !subMenu.isCollapsed;
                    return;
                }
                if (partsStates.indexOf(subMenu.state) != -1) {
                    // 点击菜单跳转产品
                    var nn = "oss-bjss";
                    var arr, bjcookie, reg = new RegExp("(^| )" + nn + "=([^;]*)(;|$)");
                    if (arr = document.cookie.match(reg)) {
                        bjcookie = unescape(arr[2]);
                    }
                    var urlTemp = subMenu.partsUrl + bjcookie;
                    window.open(urlTemp, '_blank')
                } else {
                    $state.go(subMenu.state)
                }
            };

            // 左侧菜单区域展开折叠
            $scope.toggleLeftMenu = function () {
                if (angular.isUndefined($scope.subMenu.children) || $scope.subMenu.children.length === 0) {
                    return;
                }

                if (noClickSideBarStates.includes(curMenuStateName)) {
                    // 如果是廉情预警dashboard页，不允许 操作 左侧菜单的 折叠 和 展示
                    return;
                }

                $scope.app.settings.sideBar = !$scope.app.settings.sideBar;
            };

            $scope.goUrl = function (state) {
                $scope.subMenu.children = [];
                $state.go(state);
            };

            $scope.logout = function () {
                UserContextService.Logout();
            };

            EventBus.Subscribe("getUserInfo", getUserInfo);

            $rootScope.curUser = {};
            function getUserInfo(data) {
                var dataT = data || {};
                $rootScope.curUser = dataT;
                $rootScope.isSuperAdmin = dataT.roleIds[0] == '1'; // 超级管理员
                $rootScope.needHide = ['wjguanli'].includes(dataT.loginName)
                setWaterMark(); // 系统加水印
            }

            EventBus.Subscribe("getSelfCompanyInfo", getSelfCompanyInfo);

            // 判断当前企业
            $rootScope.curOrg = {};
            function getSelfCompanyInfo(data) {
                var dataT = data || {};
                dataT.masterOrgIds = dataT.masterOrgIds || [];

                // 当前登录公司
                $rootScope.curOrg = dataT;
                // 当前登录公司orgId
                $rootScope.curOrgId = dataT.orgId;
                // 当前登录公司类型
                $rootScope.curOrgType = dataT.companyType;

                // 判断当前用户是不是主机厂
                $rootScope.isZHJCH = dataT.isSap === 1;
                $rootScope.sapNum = dataT.isSap || 0;

                // 判断当前用户是哪家主机厂
                judgeCompanyInfo(dataT.orgId);
            }
            function judgeCompanyInfo(orgId) {
                $rootScope.isSWY = window.SWY_ORG_IDs?.includes(orgId);
                $rootScope.isJCH = window.JCH_ORG_IDs?.includes(orgId);
                $rootScope.isTJ = window.TJ_ORG_IDs?.includes(orgId);
                $rootScope.isLDD = window.LDD_ORG_IDs?.includes(orgId);
                $rootScope.isZX = window.ZX_ORG_IDs?.includes(orgId);
                $rootScope.isWJ = window.WJ_ORG_IDs?.includes(orgId);
                $rootScope.isJCHK = window.JCHK_ORG_IDs?.includes(orgId);
                $rootScope.isCHY = window.CHY_ORG_IDs?.includes(orgId);
                $rootScope.isTeJ = window.TeJ_ORG_IDs?.includes(orgId);
                $rootScope.isSCH = window.SCH_ORG_IDs?.includes(orgId);
                $rootScope.isNY = window.NY_ORG_IDs?.includes(orgId);
                $rootScope.isNJ = window.NJ_ORG_IDs?.includes(orgId);

                $rootScope.isDL = window.DL_ORG_IDs?.includes(orgId);
                $rootScope.isZHL = window.ZHL_ORG_IDs?.includes(orgId);
                $rootScope.isYH = window.YH_ORG_IDs?.includes(orgId);
                
                $rootScope.isZL = window.ZL_ORG_IDs?.includes(orgId);
                $rootScope.isXF = window.XF_ORG_IDs?.includes(orgId);
                $rootScope.isKJ = window.KJ_ORG_IDs?.includes(orgId);
            }

            $scope.currentLan = $translate.preferredLanguage();
            $rootScope.isEN = judgeEnvIsEn($scope.currentLan);
            $rootScope.isES = judgeEnvIsEs($scope.currentLan);
            $scope.switchLan = function (val) {
                $rootScope.isEN = judgeEnvIsEn(val);
                $rootScope.isES = judgeEnvIsEs(val);
                localStorage.setItem('lang', val);
                window.location.reload();
            };

            function judgeEnvIsEn(lan) {
                return lan == 'en-US'
            }
            function judgeEnvIsEs(lan) {
                return lan == 'es-ES'
            }


            EventBus.Subscribe("go2otherMenuPage", go2otherMenuPage);

            function go2otherMenuPage(data) {
                var item = {
                    children: []
                };
                var stateName = data.name;
                var parentStateName = stateName.substr(0, stateName.lastIndexOf('.'))
                for (var i = 0; i < $scope.allMenus.length; i++) {
                    if ($scope.allMenus[i].state === parentStateName) {
                        item = $scope.allMenus[i];
                        break;
                    }
                }
                $rootScope.primaryMenuItem = item;
                $rootScope.subMenu = angular.copy(item);
                $state.go(stateName, data.params);
            }
            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("getUserInfo", getUserInfo);
                EventBus.Unsubscribe("getSelfCompanyInfo", getSelfCompanyInfo);
                EventBus.Unsubscribe("go2otherMenuPage", go2otherMenuPage);
            });

            function createWaterMark() {
                const data = $scope.curUser || {}
                const canvasObj = document.createElement('canvas');
                const canvas2d = canvasObj.getContext('2d');
                canvasObj.width = 600;
                canvasObj.height = 260;
                canvas2d.font = '24px Arial';
                canvas2d.fillStyle = 'rgba(204,204,204,.2)';
                canvas2d.rotate((-10 / 180) * Math.PI);
                canvas2d.fillText('广汽仓储平台内部文件，请勿外传！', 0, canvasObj.height / 3);
                canvas2d.fillText(`广汽传祺公司&&${data.loginName}&&${data.name}`, 0, canvasObj.height / 2);
                const base64Url = canvasObj.toDataURL('image/png');
                return base64Url;
            }

            function setWaterMark() {
                const id = 'globalWaterMark';
                const url = createWaterMark();
                const target = document.getElementById(id);
                if(target){
                  document.body.removeChild(target)
                }

                const divObj = document.createElement('div');
                divObj.id = id;
                const styleStr = `
                              position:fixed;
                              top:0;
                              left:0;
                              bottom:0;
                              right:0;
                              z-index:999999;
                              pointer-events:none;
                              background-image:url('${url}')`;
                divObj.setAttribute('style', styleStr);
                document.body.appendChild(divObj);

                // 监听DOM变动
                const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
                if (MutationObserver) {
                  let waterMarkOb = new MutationObserver(function () {
                    const _globalWatermark = document.querySelector(`#${id}`);
                    // 当样式或者水印元素dom节点有改动时会重新绘制
                    if (!_globalWatermark || _globalWatermark.getAttribute('style') !== styleStr) {
                      waterMarkOb.disconnect();
                      waterMarkOb = null;
                      setWaterMark();
                    }
                  });
                  // 指定观察对象
                  waterMarkOb.observe(document.body, {
                    attributes: true,
                    subtree: true,
                    childList: true,
                  });
                }
            }

            $scope.switchOther = function() {
                UserContextService.ClearStorageExcludeLang();

                var hostOrigin
                if (!window.location.origin) {
                    hostOrigin = window.location.protocol + '//' + window.location.host;
                } else {
                    hostOrigin = window.location.origin;
                }
                window.open(`${hostOrigin}/parts/loginOtherAccount?redirectUrl=${window.location.href}`, '_self');
            };

            (function () {
                getAuthMenu();

                UserContextService.GetAuthCodes();
                UserContextService.GetSelfCompanyInfo().then(() => {
                    UserContextService.GetUserInfo();
                });
                UserContextService.GetPageCheckStock();
            })();
        }]);
})(window, window.angular);
